package com.ljx.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljx.Domain.Category;
import com.ljx.Domain.R;
import com.ljx.Service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    /**
     * 根据category类新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        //调用service层,添加分类
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * category类的分页展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> CategoryPage(int page, int pageSize) {
        //创建page对象，保存当前页和每页展示数
        Page<Category> categoryPage = new Page<>(page, pageSize);
//        //创建wrapper对象，设置条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        //调用service层，传入数据
        Page<Category> category = categoryService.page(categoryPage, wrapper);
        return R.success(category);
    }

    @DeleteMapping
    public R<String> delectCategory(long ids) {
        //调用service层方法，通过id删除
        categoryService.Delete(ids);
        return R.success("删除成功！");
    }

    /**
     * 通过id修改数据
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> modify(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

    @GetMapping("/list")
    public R<List<Category>> categoryList(Category category) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }


}
